<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="解决方案名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入解决方案名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="级别" prop="level">
        <el-input-number v-model="queryParams.level" 
        controls-position="right" placeholder="请输入解决方案级别" clearable 
        @keyup.enter.native="handleQuery" :min="0" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plainicon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:solution:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table 
      v-if="refreshTable"
      v-loading="loading" 
      :data="solutionList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="ID" prop="id" width="90" />
      <el-table-column label="解决方案名称" prop="name" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="文描图" prop="img"  width="220" :show-overflow-tooltip="true">
        <template slot-scope="scope" v-if="scope.row.level === 1">
          <el-image @click="bigImg(`${scope.row.img}`)"
            style="width: 120px; height: 120px; margin-bottom:-4px"
            :src="scope.row.img"
            :preview-src-list="srcList"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="级别" prop="level"  width="90">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.kh_type_level" :value="scope.row.level"/>
        </template>  
      </el-table-column>
      <el-table-column label="排序" prop="sort"  width="90" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
       
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:solution:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['product:solution:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:solution:remove']"
          >删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditSeo(scope.row)">SEO设置</el-button>
          <el-button v-if="scope.row.parentId === 0" size="mini" type="text" icon="el-icon-upload" @click="handleSetImg(scope.row)">设置文描</el-button>
        </template>
      </el-table-column>
    </el-table>

    <seoDetail ref="seo" />

     <!-- 添加或修改解决方案对话框 -->
     <el-dialog :title="title" :visible.sync="open" width="400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24" v-if="form.id === undefined">
            <el-form-item label="解决方案类型" prop="parentId">
              <treeselect v-model="form.parentId" :options="solutionOptions" :normalizer="normalizer" placeholder="选择上级解决方案" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="解决方案名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入解决方案名称" :maxlength="30" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24" v-if="form.parentId === 0">
            <el-form-item label="解决方案内容" prop="content">
              <el-input 
                type="textarea"
                :autosize="{ minRows: 4, maxRows: 9999}" 
                v-model="form.content" 
                placeholder="请输入解决方案内容" 
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 设置文描对话框 -->
    <el-dialog :title="title" :visible.sync="options.open" width="900px" append-to-body @opened="modalOpened"  @close="closeDialog">
      <el-row>
        <el-col :xs="24" :md="12" :style="{height:setHeight+'px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="options.visible"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height:setHeight+'px'}">
          <div class="logo-upload-preview">
            <img :src="previews.url" :style="previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :sm="3" :xs="3">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small">
              选择
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :sm="2" :xs="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { listSolution,listSolutionExcludeChild,getSolution,addSolution,updateSolution,delSolution,uploadFileImg} from "@/api/product/solution";
import Treeselect from "@riophae/vue-treeselect";
import { VueCropper } from "vue-cropper";
import { debounce } from '@/utils'
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Solution",
  dicts: ['kh_type_level'],
  components: { 
    Treeselect, 
    VueCropper,
    seoDetail: () => import('@/views/content/seo/detail'),
  },
  props: {
    setWidth:{
      type:Number,
      default:500
    },
    setHeight:{
      type:Number,
      default:350
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品类型表格数据
      solutionList: [],
      // 产品类型树
      solutionOptions:[],
      srcList:["https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg"],
      // 查询参数
      queryParams: {
        name: undefined,
        level: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "解决方案名称值不能为空", trigger: "blur" }
        ],
        parentId: [
           { required: true, message: "解决方案的父类型不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序值不能为空", trigger: "blur" }
        ]
      },
      options: {
        id: undefined,
        img: undefined,
        // 是否显示弹出层
        open: false,
        // 是否显示cropper
        visible: false,
        // 弹出层标题
        title: "修改",
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: this.setWidth / 2, // 默认生成截图框宽度
        autoCropHeight: this.setHeight / 2, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        outputType:"png" // 默认生成截图为PNG格式
      },
      previews: {},
      resizeHandler: null,
      seoData: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询产品类型列表 */
    getList() {
      this.loading = true;
      this.solutionList = [];
      listSolution(this.queryParams).then(response => {
          //this.solutionList = this.handleTree(response.data, "id");
          let sourceSolutionList = this.handleTree(response.data, "id");
          if (sourceSolutionList !== undefined && sourceSolutionList.length > 0) {
            for (let i = 0; i < sourceSolutionList.length; i++) {
              const solution = sourceSolutionList[i];
              solution['img'] = process.env.VUE_APP_BASE_API + solution['img'];
              this.solutionList.push(solution);
            }
          }
          this.loading = false;
        }
      );
    },
   
     /** 转换数据结构 */
     normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        parentId: undefined,
        sort: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      if (row != undefined) {
        this.form.parentId = row.id;
      }
      this.open = true;
      this.title = "添加解决方案";
      listSolution().then(response => {
        this.solutionOptions = this.handleTree(response.data, "id");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id 
      getSolution(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改解决方案";

        listSolutionExcludeChild(row.id).then(response => {
          this.solutionOptions = this.handleTree(response.data, "id");
          if (this.solutionOptions.length == 0) {
            const noResultsOptions = { deptId: this.form.parentId, deptName: this.form.parentName, children: [] };
            this.solutionOptions.push(noResultsOptions);
          }
        });
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateSolution(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSolution(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id
      this.$modal.confirm('是否确认删除参数编号为"' + id + '"的数据项？').then(function() {
          return delSolution(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    bigImg(url) {
      this.srcList[0] = url;
    },
    /**设置文描 */
    handleSetImg(row) {
      this.options.open = true;
      this.options.id = row.id;
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.options.visible = true;
      if (!this.resizeHandler) {
        this.resizeHandler = debounce(() => {
          this.refresh()
        }, 100)
      }
      window.addEventListener("resize", this.resizeHandler)
    },
    // 刷新组件
    refresh() {
      this.$refs.cropper.refresh();
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.options.img = reader.result;
        };
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData(); 
        formData.append('id', this.options.id);
        formData.append('img', data);
        uploadFileImg(formData).then(response => {
          this.options.open = false;
          let imgUrl = response.imgUrl;
          this.options.img = process.env.VUE_APP_BASE_API + imgUrl;
          this.getList();
          this.$modal.msgSuccess("上传成功");
          this.options.visible = false;
        });
      });
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    // 关闭窗口
    closeDialog() {
      this.options.visible = false;
      window.removeEventListener("resize", this.resizeHandler)
    },
    handleEditSeo(row) {
      this.seoData.pageType = 'solution',
      this.seoData.pageId = row.id;
      this.$refs.seo.open(this.seoData);
    },

  }

}
</script>